package com.jy.admin.jobs;

import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.BogConfigDao;
import com.jy.admin.db.dao.BogLogDao;
import com.jy.admin.db.dao.PendingLogDao;
import com.jy.admin.db.entity.BogConfigEntity;
import com.jy.admin.db.entity.BogLogEntity;
import com.jy.admin.db.entity.PendingLogEntity;
import com.jy.admin.enums.PendingStatusEnum;
import com.robert.vesta.util.IdUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.EnglishOCRRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/12/30
 * Time: 5:39 下午
 */
@Service
public class BobotSentJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(BobotSentJob.class);

    @Autowired
    private BogLogDao bogLogDao;

    @Autowired
    private BogConfigDao bogConfigDao;

    @Autowired
    private PendingLogDao pendingLogDao;

    @Autowired
    private ApolloConfigUtil configUtil;

    @Scheduled(fixedDelay = 1000L * 10)
    public void run() {
        List<PendingLogEntity> listBySendStatus = pendingLogDao.getListByRobotIdAndStatus(null, PendingStatusEnum.detail_ready.getStatus());
        LOGGER.info("== 等待转发的消息数量为 ==,size:{}", listBySendStatus.size());

        if (!configUtil.getSendSwitch()) {
            LOGGER.info("== 等待转发的消息  开关未打开==");
            return;
        }

        listBySendStatus.forEach(bot -> {
            String code = bot.getTransctionNo();
            if(StringUtils.isEmpty(code))
                code = configUtil.getOrcSwitch() ? get12Code(bot.getImgUrl()) : "请手动获取";

            BogConfigEntity bogConfigEntity = bogConfigDao.selectByFrom(bot.getFromGroup());
            if (bogConfigEntity == null) {
                LOGGER.info("== 等待转发的消息  找不到配置==");
                return;
            }
            try {
                String encode = URLEncoder.encode(bot.getProductName() + ",补单请回复:\n1:成功 \n2:数据无效 \n3:暂时无法处理. \n(其他情况请直接回复内容!) \n\n" + "12码(参考):\n" + code + "\n" + bot.getRequstDetail(), "UTF-8");

                String bogMsgId = "DF" + IdUtils.genId() + "";
                if (!configUtil.getNoSendConfigCodes().contains(bogConfigEntity.getConfigCode())) {
                    String res = HttpUtil.getPage("https://api.telegram.org/bot" + bogConfigEntity.getTelegramBotToken() + "/sendPhoto?chat_id=" + bogConfigEntity.getTelegramChatId() + "&photo=" + bot.getImgUrl() + "&caption=" + encode);
                    LOGGER.info("== post to telegram res ==,res:{}", res);
                    Any result = JsonIterator.deserialize(res).get("result");
                    bogMsgId = result.get("message_id").toString() + "#" + result.get("chat").get("id").toString();
                }

                bot.setTelMsgId(bogMsgId)
                        .setStatus(PendingStatusEnum.send_success.getStatus())
                        .setTransctionNo(code);

                pendingLogDao.updateByPrimaryKey(bot);
            } catch (UnsupportedEncodingException e) {
                bot.setStatus(PendingStatusEnum.send_fail.getStatus());
                pendingLogDao.updateByPrimaryKey(bot);
                LOGGER.error("== 发送到telegram消息异常 ==,logId:{}", bot.getId(), e);
            }

        });

    }


    public static String get12Code(String imageUrl) {
        Credential cred = new Credential("AKIDxiCQN3SaR2LN8cpkOlsjKfkY4JHyPYQ1", "MRFmulKdeOs51g4B1Zqqa3F9m9E2YonV");
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        OcrClient client = new OcrClient(cred, "ap-hongkong", clientProfile);
        EnglishOCRRequest req = new EnglishOCRRequest();
        req.setImageUrl(imageUrl);

        String transactionNo = "";
        try {
            HashMap<String, String> resMap = new HashMap<>();
            client.EnglishOCR(req).toMap(resMap, "");
            LOGGER.info("== 补单ocr结果 ==,res:{}", JsonStream.serialize(resMap));
            for (String rs : resMap.values()) {
                rs = rs.replaceAll(" ", "");
                if (rs.length() < 12) {
                    continue;
                }
                boolean matches = rs.matches("^.*\\d{12}.*$");
                if (matches && rs.length() == 12) {
                    transactionNo += rs + ",";
                }
            }

            if (transactionNo.length() > 12) {
                transactionNo = transactionNo.substring(0, transactionNo.length() - 1);
            }

            return transactionNo;
        } catch (TencentCloudSDKException e) {
            LOGGER.info("== 补单的图片OCR调用失败 ==,imageUrl:{}", imageUrl, e);
        }
        return "请手动获取";
    }

    public static void main(String[] args) {
        String code = get12Code("http://dc-oss2.oss-ap-south-1.aliyuncs.com//excel/test/237098644463944249.png");
        LOGGER.info("== 获取到的12码 ==,code:{}", code);
    }
}
